import React, { useState, useEffect, useRef } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import {
	MenuFoldOutlined,
	MenuUnfoldOutlined,
	UserOutlined
} from '@ant-design/icons';
import { Layout, Avatar, Menu, Dropdown, Drawer, Descriptions, Form } from 'antd'
import { connect, useSelector } from 'react-redux'
import { createChangeCollapsedAction } from '../../redux/actions/Collapsed.js'
import { getPersonalServiceData, getRights, getUserByName } from '../../utils/request/get.js';
import _ from 'lodash'
import * as echarts from 'echarts'
import PersonalCenter from './PersonalCenter.js';

const { Header } = Layout

function TopHeader(props) {
	const token = useSelector(state => state.TokenReducer.token)
	const [title, setTitle] = useState('')
	const [user, setUser] = useState(null)
	const [rights, setRights] = useState(null)
	const [visible, setVisible] = useState(false)
	const [personalVisible, setPersonalVisible] = useState(false)
	const [categories, setCategories] = useState([])
	const [auditStates, setAuditStates] = useState([])
	const [pieChart, setPieChart] = useState(null)
	const [auditPieChart, setAuditPieChart] = useState(null)
	const categoryRef = useRef()
	const auditStateRef = useRef()
	const [form] = Form.useForm()

	let navigate = useNavigate()
	let location = useLocation()
	const { collapsed } = props.CollapsedReducer
	useEffect(() => {
		async function fetchData() {
			if (token) {
				const res = await getRights(token.roleId)
				if (res) {
					setRights(res)
				}
				getUserByName(token.username).then(res => {
					const data = res.data.user
					if (data) {
						setUser(data)
					}
				})
				const { categories, auditStates } = await getPersonalServiceData(token.userId)
				if (categories) {
					setCategories(categories)
				}
				if (auditStates) {
					setAuditStates(auditStates)
				}
			}
		}
		fetchData()
	}, [token])

	useEffect(() => {
		if (rights) {
			rights.forEach(item => {
				if (item.key === location.pathname) {
					setTitle(item.title)
				} else if (item.children.length > 0) {
					item.children.forEach(data => {
						if (data.key === location.pathname) {
							setTitle(data.title)
						}
					})
				}
			})
		}
	}, [location.pathname, rights])

	const handleMenuClick = (item) => {
		switch (item.key) {
			case "2":
				setVisible(true)
				setTimeout(() => {
					renderPersonal()
				}, 0)
				return
			case "3":
				setPersonalVisible(true)
				return
			case "4":
				localStorage.removeItem('token')
				navigate('/login')
				return
			default:
				return
		}
	}

	const renderPersonal = () => {
		const categoryGroup = _.groupBy(categories, item => item.title)
		let categoryList = []
		for (let key in categoryGroup) {
			categoryList.push({
				name: key,
				value: categoryGroup[key][0]?.num
			})
		}
		configMyChart("category", categoryRef, categoryList, "当前用户业务分类图示", ['55%', '75%'])
		const auditStateGroup = _.groupBy(auditStates, item => item.title)
		// console.log(auditStateGroup);
		let auditList = []
		for (let key in auditStateGroup) {
			auditList.push({
				name: key,
				value: auditStateGroup[key][0]?.num
			})
		}
		// console.log(auditList);
		configMyChart("audit", auditStateRef, auditList, "业务审核状态图示", ['80%', '100%'])
	}

	const configMyChart = (chart, ref, data, text, radius) => {
		let myChart;
		if (chart !== "audit") {
			if (!pieChart) {
				myChart = echarts.init(ref.current)
				setPieChart(myChart)
			} else {
				myChart = pieChart
			}
		} else {
			if (!auditPieChart) {
				myChart = echarts.init(ref.current)
				setAuditPieChart(myChart)
			} else {
				myChart = auditPieChart
			}
		}

		const option = {
			title: {
				text,
				left: 'center',
				top: '52%'
			},
			tooltip: {
				trigger: 'item',
				position: ['5%', '50%']
			},
			legend: {
				orient: 'vertical',
				left: 'left'
			},
			series: [
				{
					name: '数量',
					type: 'pie',
					radius,
					top: '10%',
					data,
					emphasis: {
						itemStyle: {
							shadowBlur: 10,
							shadowOffsetX: 0,
							shadowColor: 'rgba(0, 0, 0, 0.5)'
						}
					}
				}
			]
		}
		myChart.setOption(option)
	}

	const items = [
		{
			key: '1',
			label: (function () {
				if (user) {
					const { Role } = user
					if (Role) {
						return Role.roleName
					}
				}
				return ""
			})()
		},
		{
			key: '2',
			label: "个人业务情况"
		},
		{
			key: '3',
			label: "账号管理"
		},
		{
			key: '4',
			label: "退出",
			danger: true
		}
	]

	const menu = () => {
		return <Menu items={items} onClick={handleMenuClick} />
	}

	return (
		<>
			<Header className="site-layout-background" style={{ padding: '0 16px' }}>
				{
					React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, { className: 'trigger', onClick: () => props.changeCollapsed(!collapsed) })
				}
				&nbsp;&nbsp;&nbsp;{title}
				<div style={{ float: 'right' }}>
					欢迎<p style={{ color: 'blue', display: 'inline', margin: '2px' }}>{user && user.username}</p>回来
					<Dropdown dropdownRender={menu}>
						<Avatar size="large" icon={<UserOutlined />} style={{ margin: '5px' }} />
					</Dropdown>

				</div>
			</Header>
			<Drawer
				title="个人历史业务明细"
				placement='right'
				width={500}
				onClose={() => { setVisible(false) }}
				open={visible}
			>
				<div ref={categoryRef} style={{ width: "100%", height: "600px" }}></div>
				<div ref={auditStateRef} style={{ width: "100%", height: "200px" }}></div>
			</Drawer>
			<Drawer
				title="账号管理"
				placement='right'
				width={500}
				onClose={() => { setPersonalVisible(false) }}
				open={personalVisible}
			>
				<PersonalCenter />
			</Drawer>
		</>
	)
}

export default connect(
	state => ({
		CollapsedReducer: state.CollapsedReducer
	}),
	{ changeCollapsed: createChangeCollapsedAction }
)(TopHeader)